package com.yoomiito.app.ui.capture

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Vibrator
import android.view.View
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.oilcard.OilCardInfo
import com.yoomiito.app.paramFromUrl
import com.yoomiito.app.showToast
import com.yoomiito.app.utils.Const
import com.yoomiito.app.utils.RouterUtils
import com.yoomiito.app.utils.Type
import kotlinx.android.synthetic.main.act_capture.*
import kotlinx.android.synthetic.main.title_bar.*
import java.util.regex.Pattern


class CaptureActivity : BaseActivity<CapturePresenter>(), QRCodeView.Delegate {

    companion object {
        const val REQUESTCODE = 1
        const val RESULTCODE = 2
        fun start(context: Context) {
            val intent = Intent(context, CaptureActivity::class.java)
            context.startActivity(intent)
        }

        fun startForResult(context: Context) {
            val intent = Intent(context, CaptureActivity::class.java)
            (context as Activity).startActivityForResult(intent, REQUESTCODE)
        }
    }

    override fun getLayoutId(): Int = R.layout.act_capture

    override fun newP(): CapturePresenter = CapturePresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        iv_back_left.setOnClickListener { finish() }
        tv_center.text = "扫一扫"
        reScan.setOnClickListener {
            reScan.visibility = View.GONE
            ZXingView.startSpot()
        }
        ZXingView.setDelegate(this)
    }

    override fun onStart() {
        super.onStart()
        ZXingView.startCamera()// 打开后置摄像头开始预览，但是并未开始识别
        ZXingView.startSpotAndShowRect() // 显示扫描框，并开始识别
    }

    override fun onStop() {
        ZXingView.stopCamera()
        super.onStop()
    }

    override fun onDestroy() {
        ZXingView.onDestroy()
        super.onDestroy()
    }

    /**
     * 震动
     */
    private fun vibrate() {
        val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    /**
     * 扫描结果
     * https://m.yoomii00.com/app/oilcard/index.html?ymCode=123456
     */
    override fun onScanQRCodeSuccess(result: String?) {
        when {
            result != null && result.startsWith("https://m.yoomii00.com/app/oilcard/index.html?") -> {
                val code = result.paramFromUrl("ymCode")
                if (code.isEmpty()){
                    showErrorTip("轻触屏幕继续扫描")
                }else{
                    showLoading()
                    p.verifyCode(code)
                }
//                val regular = "(?<=(\\?|&)ymCode=).*?(?=&|$)"
//                val pattern = Pattern.compile(regular)
//                val matcher = pattern.matcher(result)
//                if (matcher.find()) {
//                    showLoading()
//                    p.verifyCode( matcher.group())
//                }else{
//                    showErrorTip("请扫描优米加油卡背部二维码\n轻触屏幕继续扫描")
//                }
            }
            else -> {
                showErrorTip("轻触屏幕继续扫描")
            }
        }
        ZXingView.stopSpot()
    }

    fun setData(info: OilCardInfo) {
        dismissLoading()
        val intent = Intent()
        intent.putExtra(Const.Common.Data, info)
        setResult(RESULTCODE, intent)
        finish()
    }

    fun showErrorTip(msg: String) {
        dismissLoading()
        reScan.visibility = View.VISIBLE
        errorTipTv.text = msg
    }

    /**
     * 摄像头环境亮度发生变化
     */
    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
        //这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        var tipText: String = ZXingView.scanBoxView.tipText
        val ambientBrightnessTip = "\n环境过暗，请打开闪光灯"
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                ZXingView.scanBoxView.tipText = tipText + ambientBrightnessTip
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
                ZXingView.scanBoxView.tipText = tipText
            }
        }
    }

    override fun onScanQRCodeOpenCameraError() {
        finish()
        "打开相机失败，请重新点击绑定".showToast()
    }

}